<template>
  <div class="lyric">
    <el-row justify="space-around" class="scroll-container" ref="scrollRef">
      <el-col :span="8" :xs="6">
        <p
          class="lyric-time"
          v-for="(item, index) in lyricTimeList"
          :key="index"
        >
          {{ item }}
        </p>
      </el-col>
      <el-col :span="12">
        <p
          class="lyric-text"
          v-for="(item, index) in lyricTextList"
          :key="index"
        >
          {{ item }}
        </p>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import emitter from '@/utils/mitt/eventbus'
import musicFormat from '../utils/index'
import localCache from '@/utils/cache'

export default defineComponent({
  setup() {
    /* 歌词数据列表 */
    const lyricList = ref<any>([])
    /* 歌词内容列表 */
    const lyricTextList = ref(null)
    /* 时间内容列表 */
    const lyricTimeList = ref(null)
    /* 歌词 */
    const lyric = ref('')
    /* 滚动组件 */
    const scrollRef = ref<any>()

    /* 在内存中获取下歌词数据 */
    if (localCache.getCache('currentLyric')) {
      lyric.value = localCache.getCache('currentLyric')
      lyricTextList.value = musicFormat.lyricFormat(lyric.value)[1]
      lyricTimeList.value = musicFormat.lyricFormat(lyric.value)[0]
    }
    /* 响应播放事件 */
    emitter.on('isPlaying', (currentIndex: any): void => {
      lyricList.value = localCache.getCache('playList')?.lyricCacheList
      lyric.value = lyricList.value[currentIndex]
      lyricTextList.value = musicFormat.lyricFormat(lyric.value)[1]
      lyricTimeList.value = musicFormat.lyricFormat(lyric.value)[0]
    })
    /* 响应滚动事件 */
    emitter.on('scoll', (t: any): void => {
      scrollStart(t)
    })
    /* 开始滚动事件
       响应滚动条数值变化
       当前滚动数值 / 100 为当前播放歌曲的 %进度
       获取歌词容器总高度，预留 300px 高度 播放进度过了 300px位置 在开始滚动
    */
    const scrollStart = (t: number) => {
      if (t / 100 > 300 / scrollRef.value.$el.offsetHeight) {
        t = t - (300 / scrollRef.value.$el.offsetHeight) * 100
        const scrollHeight = (scrollRef.value.$el.offsetHeight / 100) * t
        scrollRef.value.$el.style.transform = `translateY(-${scrollHeight}px)`
      }
    }
    return { lyricTextList, lyricTimeList, scrollRef }
  }
})
</script>

<style scoped lang="less">
.lyric {
  height: 6rem;
  overflow-y: auto;
  .scroll-container {
    transition: all linear 1s;
    p {
      color: #fff;
      padding: 20px 0 4px 20px;
    }
    .lyric-time {
      color: rgb(185, 185, 185);
      text-align: center;
    }
  }
}
</style>
